package cn.jekun.shop.common.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.DateJsonValueProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.NotNull;
import cn.jekun.component.base.validator.annotation.RegExp;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.McCreditsDailysign;
import cn.jekun.component.core.bean.gen.McCreditsJournal;
import cn.jekun.component.core.bean.gen.McMember;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.ProfitService;
import cn.jekun.component.core.service.gen.McCreditsDailysignService;
import cn.jekun.component.core.service.gen.McCreditsJournalService;
import cn.jekun.component.core.service.gen.McMemberService;
@Service(CreditsDailySignService.BEAN_NAME)
public class CreditsDailySignService extends ShopBaseService{

	public static final String BEAN_NAME = "cn.jekun.shop.common.service.CreditsDailySignService";
	
	@Resource(name=McMemberService.BEAN_NAME)
	McMemberService mcMemberService;
	
	@Resource(name=McCreditsDailysignService.BEAN_NAME)
	McCreditsDailysignService mcCreditsDailysignService;
	
	@Resource(name = McCreditsJournalService.BEAN_NAME)
	McCreditsJournalService mcCreditsJournalService;
	
	@Resource(name=ProfitService.BEAN_NAME)
	ProfitService profitService;
	
	@Override
	public String getNamespace() {
		return "SHOP_CREDITS_DAILY_SIGN";
	}
	/**
	 * 每日签到日志(同时返回当天是否已经签到)
	 * @param userId
	 * @param page
	 * @return
	 */
	public JSONObject getSignLog(
			@RegExp(regExp="^[0-9]{0,50}$",message="用户编码非法")
			@RsUser.AnnoUserId
			String userId, 
			@NotNull(message="分页对象不能为空")
			Page page) {
		JSONObject jsonObject = new JSONObject();
		//基本验证
		if(StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户代码不能为空");
		}
		try{
			Map map = new HashMap();
			map.put(McMember.COL_USER_ID, userId);
			map.put(McMember.COL_SHOP_ID, Constants.COM_SHOP_ID);//公司商家
			//今天是否已经签到
			boolean signed = this.exists(map);
			jsonObject.put("signed", signed);//今天是否已经签到
			//签到日志
			List<McCreditsDailysign> logs = this.list(map,page);
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss")); 
			
			jsonObject.put("logs", JSONArray.fromObject(logs, jsonConfig));
			jsonObject.put("totalCount", page.getTotalCount());
			jsonObject.put("pages", page.getPages());
			return this.executeRerutn(jsonObject);
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		return this.executeRerutnFail(jsonObject);
	}
	/**
	 * 每日签到，获取积分
	 * @param userId
	 * @return
	 */
	public JSONObject dailySign(
			@RegExp(regExp="^[0-9]{0,50}$",message="用户编码非法")
			@RsUser.AnnoUserId
			String userId) {
		String shopId = Constants.COM_SHOP_ID;
		JSONObject jsonObject = new JSONObject();
		//基本验证
		/*if(StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户代码不能为空");
		}*/
		try{
			Map map = new HashMap();
			map.put(McMember.COL_USER_ID, userId);
			map.put(McMember.COL_SHOP_ID, shopId);//公司商家
			
			//今天是否已经签到
			boolean signed = this.exists(map);
			if (signed) {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"您今天已经签到，不能重复签到");
			}
			double credits = this.profitService.getDailySignCredit();//积分规则
			if (credits<=0) {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"对不起，签到送积分活动暂停，请关注下次开放。");
			}
			//会员是否存在
			SqlUtis.prepareSql(map
					,SqlUtis.getSQLRequired(map, McMember.COL_USER_ID)
					,SqlUtis.getSQLRequired(map, McMember.COL_SHOP_ID)
					);
			McMember mcMember = this.mcMemberService.one(map);
			if (mcMember == null) {//不存在，增加
				mcMember = new McMember();
				mcMember.setCredits(credits);
				mcMember.setLevelId(Constants.MC_MEMBER_LEVEL.PRIMARY);
				mcMember.setMemberTypeId(Constants.MC_MEMBER_TYPE.APP);
				mcMember.setShopId(shopId);
				mcMember.setUserId(userId);
				Map insertMap = new HashMap();
				insertMap.put("mcMember", mcMember);
				String memberId = (String) this.mcMemberService.insert(insertMap);
				mcMember.setMemberId(memberId);
			}else{
				//更新积分
				Map updateMap = new HashMap();
				McMember updateMember = new McMember();
				updateMember.setMemberId(mcMember.getMemberId());
				updateMember.setCredits(mcMember.getCredits()+credits);//增加积分
				updateMap.put("mcMember", updateMember);
				updateMap.put(McMember.COL_MEMBER_ID,mcMember.getMemberId());
				SqlUtis.prepareSql(updateMap,SqlUtis.getSQLRequired(updateMap, McMember.COL_MEMBER_ID));
				this.mcMemberService.update(updateMap);//更新积分
				
				mcMember.setCredits(updateMember.getCredits());//新的积分
			}
			
			//增加积分流水
			Map insertJournalMap = new HashMap();
			McCreditsJournal mcCreditsJournal = new McCreditsJournal();
			mcCreditsJournal.setCreateName(userId);
			mcCreditsJournal.setCredits(credits);
			mcCreditsJournal.setCreditsBalance(mcMember.getCredits());
			mcCreditsJournal.setMemberId(mcMember.getMemberId());
			mcCreditsJournal.setOperationTypeId(Constants.MC_CREDITS_OPERATION_TYPE.ADD);
			mcCreditsJournal.setShopId(shopId);
			mcCreditsJournal.setMemo("每日签到");
			insertJournalMap.put("mcCreditsJournal", mcCreditsJournal);
			mcCreditsJournalService.insert(insertJournalMap );
			
			//增加签到日志
			McCreditsDailysign mcCreditsDailysign = new McCreditsDailysign();
			mcCreditsDailysign.setCreateName(userId);
			mcCreditsDailysign.setCredits(credits);
			mcCreditsDailysign.setType(Constants.DAILYSIGN_TYPE.Day);
			mcCreditsDailysign.setMemberId(mcMember.getMemberId());
			mcCreditsDailysign.setCreateName(userId);
			Map insertMap = new HashMap();
			insertMap.put("mcCreditsDailysign", mcCreditsDailysign);
			this.mcCreditsDailysignService.insert(insertMap);
			
			//返回结果
			return this.executeRerutn(jsonObject);
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		return this.executeRerutnFail(jsonObject);
	}
}
